﻿using Newtonsoft.Json.Linq;
using per.esmool.utils;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FlowSimulate {

    public class Suit {

        public Suit(string flowDefinitionPath, string moduleDefinitionPath, string costDefinitionPath) {
            this.flowDefinitionPath = flowDefinitionPath;
            this.moduleDefinitionPath = moduleDefinitionPath;
            this.costDefinitionPath = costDefinitionPath;

            this.flowDefinition = LoadYaml(this.flowDefinitionPath);
            this.moduleDefinition = LoadYaml(this.moduleDefinitionPath);
            this.costReader = new CostReader(this.costDefinitionPath);
        }

        readonly string flowDefinitionPath;
        readonly string moduleDefinitionPath;
        readonly string costDefinitionPath;

        readonly CostReader costReader;
        readonly Dictionary<string, JObject> flowDefinition;
        readonly Dictionary<string, JObject> moduleDefinition;

        public List<JObject> Flows => [.. this.flowDefinition.Values];

        public List<JObject> Modules => [.. this.moduleDefinition.Values];

        public CostReader CostReader => this.costReader;

        public JObject GetStage(string key) {
            return this.flowDefinition[key];
        }

        public JObject GetModule(string key) {
            return this.moduleDefinition[key];
        }

        private static Dictionary<string, JObject> LoadYaml(string yamlPath) {
            var array = YamlKit.ParseFile<JArray>(yamlPath);
            var merged = JsonKit.Merge(array, "key", new () {
                MergeArrayHandling = MergeArrayHandling.Replace
            });
            var result = merged.ToDictionary(x => x.Value<string>("key"), x => x as JObject);
            return result;
        }

        internal string PrintSelf() {
            var builder = new StringBuilder();

            builder.AppendLine("## COSTS");
            builder.AppendLine(this.costReader.PrintSelf());

            return builder.ToString();
        }
    }
}
